#include "core/main.h"

void GameTetrisBasic::Init()
{
    _spriteBlock = _collection.AddSprite(Bitmap::LoadFile("../assets/tetrisBasic/block.png"), "block");
    
    _observedIntNames.push_back("pieceX");
    _observedIntNames.push_back("pieceY");
    _observedIntNames.push_back("pieceType");
    _observedIntNames.push_back("score");
    _observedIntNames.push_back("rotation");
    
    _tiles.Allocate(TetrisConstants::boardHeight, TetrisConstants::boardWidth);
}

void GameTetrisBasic::NewPiece()
{
    _piecePos = Vec2i(Constants::NESGridWidth / 2, 0);
    _rotation = 0;
    _startFrame = 1;
    _pieceType = rand() % TetrisConstants::pieceCount;
}

void GameTetrisBasic::NewGame()
{
    for(UINT y = 0; y < _tiles.Rows(); y++)
    {
        for(UINT x = 0; x < _tiles.Cols(); x++)
        {
            _tiles(y, x) = -1;
        }
    }
    
    _score = 0;

    NewPiece();
}

ControllerState GameTetrisBasic::SimpleAI()
{
    ControllerState result;
    return result;
}

void GameTetrisBasic::Step(ControllerState &controller)
{
    if(controller.up()   ) _rotation++;
    if(controller.down() ) _rotation--;
    if(controller.left() ) _piecePos.x--;
    if(controller.right()) _piecePos.x++;

    _piecePos.x = Math::Bound(_piecePos.x, 0, TetrisConstants::boardWidth - 1);
    _piecePos.y = Math::Bound(_piecePos.y, 0, TetrisConstants::boardHeight - 1);
    _rotation = Math::Mod(_rotation, 4);
    _startFrame = 0;

    MakeFrameSprites();
}

void GameTetrisBasic::MakeFrameSprites()
{
    _activeFrame.sprites.clear();
    for(UINT y = 0; y < _tiles.Rows(); y++)
    {
        for(UINT x = 0; x < _tiles.Cols(); x++)
        {
            int curTile = _tiles(y, x);
            if(curTile >= 0) _activeFrame.sprites.push_back(SpriteLocation(Vec2i(x * 8, y * 8), curTile, 0));
        }
    }

    //_activeFrame.sprites.push_back(SpriteLocation(_charaterPos, 0, 1));
}
